package com.itheima.api;

import com.itheima.domain.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import javax.annotation.Resource;

@DubboService
public class UserLikeApiImpl implements UserLikeApi{

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 保存喜欢信息
     * @param userId
     * @param userLikeId
     * @return
     */
    @Override
    public Boolean love(Long userId, Long userLikeId,boolean isLike) {

        try {
            //查询数据是否已经存在
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(userLikeId));
            UserLike one = mongoTemplate.findOne(query, UserLike.class);
            if (one == null){
                //数据不存在，插入新数据
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(userLikeId);
                userLike.setIsLike(isLike);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                mongoTemplate.insert(userLike);
            }else {
                //数据存在，更新数据
                Update update = Update.update("isLike",isLike).set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
